package com.qingneng.budget.web;



import java.security.Principal;

import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.context.HttpSessionContextIntegrationFilter;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.ui.WebAuthenticationDetails;
import org.apache.log4j.Logger;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;
import com.qingneng.budget.security.CurrentUser;
import com.qingneng.budget.security.IUserDetails;
import com.qingneng.budget.service.sdk.IUserInfoService;
import com.qingneng.budget.util.BaseAction;
import com.qingneng.budget.util.DigestUtils;
import com.qingneng.budget.vo.Userinfo;

public class LoginAction extends BaseAction implements ModelDriven<Userinfo>{
	
	private static final Logger logger = Logger.getLogger(LoginAction.class);
	
	public Userinfo userInfo  = new Userinfo();
	
	public IUserInfoService userInfoService;
	
	public  LoginAction(){
		
	}
	
	public  LoginAction( IUserInfoService userInfoService){
		this.userInfoService = userInfoService;
	}
	
	public String execute(){
		if(logger.isDebugEnabled()){
			logger.debug("+++ begin login ++++");
		}
	/*logger.info("useraccount: ["+userInfo.getUseraccount()+"]  is login");
		userInfo.setUserpassword(DigestUtils.md5Hex(userInfo.getUserpassword()));
		Userinfo user = userInfoService.getUserInfo(userInfo);
		if(user!=null && userInfo.getUseraccount().equals(user.getUseraccount())){
			logger.info("useraccount:"+userInfo.getUseraccount()+" login success");
			
			try{
				
			Authentication auth=null;	
			UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken
			(userInfo.getUseraccount(), userInfo.getUserpassword());
			authReq.setDetails(new WebAuthenticationDetails(this.getRequest()));		
			AuthenticationManager authenticationManager=(AuthenticationManager)super.getBean("authenticationManager");
			auth=authenticationManager.authenticate(authReq);
			//将 Authentication 信息放入 context 中
			SecurityContext secCtx = SecurityContextHolder.getContext();		
			secCtx.setAuthentication(auth);
			
			//Principal principal = (Principal)auth.getPrincipal();
			//principal.getName();
				
			//this.getRequest().getSession().setAttribute("user", auth.getPrincipal());
			this.getRequest().setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY, secCtx);
			
			}catch (Exception e) {
				e.printStackTrace();
			}
				
					
			// 放入session中	
			setUserInfo(user);
			
			userInfo.setMessage("success");
			
		}else{
			userInfo.setMessage("failure");
		}*/
		IUserDetails user = CurrentUser.getUser();
		
		
		
		return Action.SUCCESS;
	}
	
	public Userinfo getModel() {
		return userInfo;
	}

}
